<!-- 锁定 -->
<template>
  <basic-container class="production-page">
    <div class="lockPage">
      <!-- 产品 -->
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span class="title">产品</span>
          <el-button style="float: right" size="small" icon="el-icon-lock" type="primary" @click="lock('PRODUCT')">锁定</el-button>
        </div>
        <el-form ref="form" :model="productForm" label-width="100px" :inline="true">
          <el-form-item label="单产品条码：" class="lockpage-label">
            <el-input size="small" placeholder="请输入单产品条码" v-model="productForm.name"></el-input>
          </el-form-item>
          <el-form-item label="批量导入：" class="lockpage-label">
            <el-upload class="upload-demo" accept=".xlsx,.xls" :http-request="uploadFile" :on-remove="handleRemove" :limit="1" :file-list="fileList">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传excel文件</div>
            </el-upload>
          </el-form-item>
        </el-form>
      </el-card>
      <!-- 物料 -->
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span class="title">物料</span>
          <el-button style="float: right" size="small" icon="el-icon-lock" type="primary" @click="lock('MATERIAL')">锁定</el-button>
        </div>
        <el-form ref="form" :model="materialForm" label-width="100px" :inline="true">
          <el-form-item label="单物料条码：" class="lockpage-label">
            <el-input size="small" placeholder="请输入单物料条码" v-model="materialForm.name"></el-input>
          </el-form-item>
          <el-form-item label="批量导入：" class="lockpage-label">
            <el-upload class="upload-demo" accept=".xlsx,.xls" :http-request="uploadMaterialFile" :on-remove="handleMaterialRemove" :limit="1" :file-list="materialFileList">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传excel文件</div>
            </el-upload>
          </el-form-item>
        </el-form>
      </el-card>
      <!-- 工单 todo:暂时注释掉-->
      <el-card class="box-card" v-if="false">
        <div slot="header" class="clearfix">
          <span class="title">工单</span>
          <el-button style="float: right" size="small" icon="el-icon-lock" type="primary" @click="lock('WORK')">锁定</el-button>
        </div>
        <el-form ref="form" :model="workForm" label-width="100px" :inline="true">
          <el-form-item label="工单：">
            <el-input placeholder="请输入工单" size="small" disabled v-model="workForm.workOrderNo" class="input-with-select">
              <el-button slot="append" icon="el-icon-search" size="small" @click="openWork"></el-button>
            </el-input>
          </el-form-item>
          <el-form-item label="工序：">
            <el-select size="small" v-model="workForm.workorderRouteId" clearable placeholder="请选择工序">
              <el-option v-for="item in workForm.workorderRouteList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    <el-dialog :title="dialog.title" :visible.sync="dialog.visible" :append-to-body="true" @close="close">
      <el-form ref="form" :model="dialog.form" :inline="false" :rules="dialog.rules">
        <el-form-item label="锁定原因:" :label-width="100" prop="lockedReason">
          <el-input type="textarea" :autosize="{ minRows: 3 }" show-word-limit maxlength="300" v-model="dialog.form.lockedReason" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" icon="el-icon-circle-plus-outline" @click="lockSubmit('form')">保 存</el-button>
        <el-button size="small" icon="el-icon-circle-close" @click="dialog.visible = false">取 消</el-button>
      </div>
    </el-dialog>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </common-modal-template>
  </basic-container>
</template>
<script>
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import { requestLock, lockFile } from '@/api/product/lock';
import { processWorkRouteByWo } from '@/api/product/productrouteManage.js';
import axios from 'axios';
export default {
  name: '',
  components: {
    CommonModalTemplate
  },
  data() {
    return {
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      timer: new Date().getTime(), //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
      materialFormData: new FormData(),
      formData: new FormData(),
      fileList: [],
      materialFileList: [],
      dialog: {
        title: '',
        visible: false,
        form: {
          lockedReason: ''
        },
        rules: {
          lockedReason: [{ required: true, message: '请输入锁定原因', trigger: 'blur' }]
        }
      },
      // 产品
      productForm: {},
      // 物料
      materialForm: {},
      // 工单
      workDefaults: {},
      workForm: {
        workOrderNo: '',
        workorderRouteId: '',
        workorderRouteList: []
      }
    };
  },
  mounted() {},
  methods: {
    lock(type) {
      switch (type) {
        case 'PRODUCT':
          this.dialog.title = '产品锁定';
          if (!this.productForm.name && this.fileList.length == 0) {
            this.$message.warning('请输入单产品条码或批量导入产品条码');
            return;
          }
          if (this.productForm.name && this.fileList.length > 0) {
            this.$message.warning('一次只能锁定单产品条码或者批量锁');
            return;
          }
          break;
        case 'MATERIAL':
          this.dialog.title = '物料锁定';
          if (!this.materialForm.name && this.materialFileList.length == 0) {
            this.$message.warning('请输入单物料条码或批量导入物料条码');
            return;
          }
          if (this.materialForm.name && this.materialFileList.length > 0) {
            this.$message.warning('一次只能锁定单物料条码或者批量锁');
            return;
          }
          break;
        case 'WORK':
          if (!this.workForm.workOrderNo && !this.workForm.workorderRouteId) {
            this.$message.warning('请输入工单或工序');
            return;
          }
          if (this.workForm.workOrderNo && this.workForm.workorderRouteId) {
            this.dialog.title = '工序锁定';
          } else {
            this.dialog.title = '工单锁定';
          }
        default:
          break;
      }
      this.dialog.visible = true;
    },
    lockSubmit(form) {
      switch (this.dialog.title) {
        case '产品锁定':
          this.productLock(form);
          break;
        case '物料锁定':
          this.materialLock(form);
          break;
        case '工单锁定':
          this.workLock(form);
          break;
        case '工序锁定':
          this.workRouteLock(form);
          break;
        default:
          break;
      }
    },
    // 产品锁定
    productLock(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.fileList.length > 0) {
            let fileParams = new FormData();
            fileParams.append('file', this.formData);
            lockFile(
              {
                lockedReason: this.dialog.form.lockedReason,
                lockedType: 'PRODUCT'
              },
              fileParams
            )
              .then(() => {
                this.$message.success('锁定成功');
                this.productForm.name = '';
                this.fileList = [];
                this.dialog.visible = false;
              })
              .catch((err) => {
                console.log(err);
              });
          } else {
            requestLock({
              lockedReason: this.dialog.form.lockedReason,
              lockedType: 'PRODUCT',
              lockedObjects: JSON.stringify([this.productForm.name])
            })
              .then(() => {
                this.$message.success('锁定成功');
                this.productForm.name = '';
                this.fileList = [];
                this.dialog.visible = false;
              })
              .catch((err) => {
                console.log(err);
              });
          }
        } else {
          return false;
        }
      });
    },
    // 物料锁定
    materialLock(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.materialFileList.length > 0) {
            let fileParams = new FormData();
            fileParams.append('file', this.materialFormData);
            lockFile(
              {
                lockedReason: this.dialog.form.lockedReason,
                lockedType: 'MATERIAL'
              },
              fileParams
            )
              .then(() => {
                this.$message.success('锁定成功');
                this.materialForm.name = '';
                this.materialFileList = [];
                this.dialog.visible = false;
              })
              .catch((err) => {
                console.log(err);
              });
          } else {
            requestLock({
              lockedReason: this.dialog.form.lockedReason,
              lockedType: 'MATERIAL',
              lockedObjects: JSON.stringify([this.materialForm.name])
            })
              .then(() => {
                this.$message.success('锁定成功');
                this.materialForm.name = '';
                this.materialFileList = [];
                this.dialog.visible = false;
              })
              .catch((err) => {
                console.log(err);
              });
          }
        } else {
          return false;
        }
      });
    },
    // 工单锁定
    workLock(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          requestLock({
            lockedReason: this.dialog.form.lockedReason,
            lockedType: 'WORKORDER',
            lockedObjects: JSON.stringify({ workOrderNo: this.workForm.workOrderNo })
          })
            .then((res) => {
              console.log(res);
              this.$message.success('锁定成功');
              this.workForm.workOrderNo = '';
              this.dialog.visible = false;
            })
            .catch((err) => {
              console.log(err);
            });
        } else {
          return false;
        }
      });
    },
    // 工序锁定
    workRouteLock(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let workorderRouteData = this.workForm.workorderRouteList.find((work) => work.value == this.workForm.workorderRouteId);
          let workorderRouteName = null;
          if (workorderRouteData) {
            workorderRouteName = workorderRouteData.label;
          }
          requestLock({
            lockedReason: this.dialog.form.lockedReason,
            lockedType: 'ROUTE',
            lockedObjects: JSON.stringify({ workOrderNo: this.workForm.workOrderNo, workorderRouteId: this.workForm.workorderRouteId, workorderRouteName })
          })
            .then(() => {
              this.$message.success('锁定成功');
              this.workForm.workOrderNo = '';
              this.workForm.workorderRouteId = '';
              this.workForm.workorderRouteList = [];
              this.dialog.visible = false;
            })
            .catch((err) => {
              console.log(err);
            });
        } else {
          return false;
        }
      });
    },
    close() {
      this.$refs.form.resetFields();
    },
    handleRemove(file, fileList) {
      this.fileList = [];
    },
    handleMaterialRemove(file, fileList) {
      this.materialFileList = [];
    },
    uploadFile(params) {
      console.log(params);
      const file = params.file;
      this.fileList = [file];
      this.formData = file;
    },
    uploadMaterialFile(params) {
      console.log(params);
      const file = params.file;
      this.materialFileList = [file];
      this.materialFormData = file;
    },
    openWork() {
      this.modalName = 'workModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择工单信息（双击进行选择）',
        url: '/api/mes-product/work-order/page',
        rowSelectionType: 'single',
        page: true,
        menu: false,
        editBtn: false,
        menuWidth: 100,
        searchLabelWidth: 100,
        columnDefs: [
          {
            label: '生产工单',
            prop: 'orderNo',
            search: true,
            order: 1,
            rules: [
              {
                required: true,
                message: '请输入生产工单',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '工单类型',
            prop: 'orderType',
            type: 'select',
            order: 2,
            rules: [
              {
                required: true,
                message: '请选择工单类型',
                trigger: 'change'
              }
            ],
            dicUrl: '/api/blade-system/dict/dictionary?code=order_type',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '工单数量',
            prop: 'planQuantity',
            type: 'number',
            minRows: 1,
            rules: [
              {
                required: true,
                message: '请输入工单数量',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '产品编码',
            prop: 'partNo',
            search: true,
            searchType: 'input',
            type: 'search',
            disabled: true,
            order: 4,
            rules: [
              {
                required: true,
                message: '请输入产品编码',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openUserCommonModal({ type: 'productCode' });
            }
          },
          {
            label: '产品名称',
            prop: 'partName',
            search: true,
            order: 5,
            disabled: true,
            rules: [
              {
                required: true,
                message: '请输入产品名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: 'BOM版本',
            prop: 'bomVersion',
            type: 'search'
          },
          {
            label: '派工产线',
            prop: 'productionLineName',
            search: true,
            searchType: 'input',
            type: 'search',
            disabled: true,
            order: 6
          }
        ]
      };
    },
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'workModal':
          this.workForm.workOrderNo = this._get(rowData, 'orderNo', '');
          this.workForm.workorderRouteList = [];
          this.workForm.workorderRouteId = '';
          // 根据工单获取工艺路线
          this.getWorkRouteList(this.workForm.workOrderNo);
          break;
        default:
          break;
      }
    },
    getWorkRouteList(id) {
      processWorkRouteByWo(id)
        .then((res) => {
          console.log(res);
          let data = res.data.data.map((d) => {
            return {
              value: d.id,
              label: d.name
            };
          });
          this.workForm.workorderRouteList = data;
        })
        .catch((err) => {});
    }
  }
};
</script>
<style lang="scss" scoped>
.lockPage {
  .box-card {
    margin-bottom: 20px;
  }
  .clearfix {
    .title {
      font-size: 1.5em;
      font-weight: bold;
    }
  }
  ::v-deep input[type='file'] {
    display: none;
  }
  ::v-deep .avue-crud__menu {
    display: none;
  }
  .lockpage-label {
    ::v-deep .el-form-item__label {
      line-height: 40px;
    }
  }
}
</style>
